<?php if (!defined('BASEPATH'))exit('No direct script access allowed');
/**
 * 好友模块控制器
 */
class Task extends MY_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->model('task_model');
        $this->load->model('subtasks_model');
        $this->load->model('account_model');
        $this->load->model('users_log_model');
        $this->load->model('finance_list_model');
    }
    //任务列表
    function index(){
        $cat = $_REQUEST['cat'];
        if ($cat){
            $this->display('task/catindex.html');
        }else{
            $tag = $this->db->select("id,name")->from("dictionary")->where(array("type"=>3))->order_by("id desc")->get()->result_array();
            $this->assign("tags", $tag);
            $this->display('task/index.html');
        }

    }
    function index1(){
        $this->display('task/index-new.html');
    }

    //任务添加
    function add() {
        //有post就是添加操作
        //检查一些必要字段是否为空，待定
        $user_info = $this->bbs_userinfo;

        if(!$user_info){//访问超时，请重新登录
            web_redirect("account/login.html".$this->get_next_request_url());
        }
        if($_POST){
            $title = $_POST['title'];
            $plat_name = $_POST['plat_name'];
            $content = $_POST['content'];
            $description = $_POST['description'];
            $sub_num = $_POST['subnum'];
            $commission = $_POST['commission'];
            $ups_commission = $_POST['ups_commission'];
            $hiups_commission = $_POST['hiups_commission'];
            $validate = $_POST['validate'];
            $cate_id = $_POST['cate_id'];
            $logo = $_POST['logo'];
            $invite_code = empty($_POST['invite_code'])?"":trim($_POST['invite_code']);
            $redirect_url = isset($_POST['redirect_url'])?$_POST['redirect_url']:"";
            $investment_money = isset($_POST['investment_money']) ? $_POST['investment_money'] : 0;
            $investment_day = isset($_POST['investment_day']) ? $_POST['investment_day'] : 0;
            $expected_money = isset($_POST['expected_money']) ? $_POST['expected_money'] : 0;
            $task_tag = isset($_POST['tags']) ? $_POST['tags'] : "";
            $img_list = isset($_POST['imglist'])?$_POST['imglist']:array();
            $bonus = empty($_POST['bonus'])?"":trim($_POST['bonus']);
            $investment_money_amount = isset($_POST['investment_money_amount']) ? $_POST['investment_money_amount'] : 0;//总投资金额
            $min_investment_money = isset($_POST['min_investment_money']) ? $_POST['min_investment_money'] : 0;//投资金额最小值
            $max_investment_money = isset($_POST['max_investment_money']) ? $_POST['max_investment_money'] : 0;//投资金额最大值
            $commission_per = isset($_POST['commission_per']) ? $_POST['commission_per'] : 0;
            $interest_rate = isset($_POST['interest_rate']) ? $_POST['interest_rate'] : 0;
            $count_url = isset($_POST['count_url']) ? $_POST['count_url'] : "";
            $task_num = isset($_POST['task_num']) ? $_POST['task_num'] : 0;
            $img_list_str = "";
            foreach ($img_list as $val){
                if(!empty($val)){
                  $img_list_str .= $val.',';
                }
            }
            $img_list = trim($img_list_str,',');
            //$cate_id = 1;//暂时定一个
            if(empty($plat_name) || empty($content) || empty($cate_id)){
                $mess['reqStatus'] = false;
                $mess['errorMsg'] = "信息填写错误1";
                echo JSON($mess);exit;
            }

            if($cate_id == 3){
                if(empty($investment_money_amount) || empty($min_investment_money) || empty($max_investment_money) || empty($commission_per)){
                    $mess['reqStatus'] = false;
                    $mess['errorMsg'] = "信息填写错误";
                    echo JSON($mess);exit;
                }
            }else{
                if(empty($commission) || empty($sub_num)){
                    $mess['reqStatus'] = false;
                    $mess['errorMsg'] = "信息填写错误2";
                    echo JSON($mess);exit;
                }
            }
            $web_config = $this->task_model->website_config();
            if($cate_id == 4){
                $commission = 10000 * $commission;
                $deposit = 0;
                $sponsorship_money = 0;
            }elseif($cate_id == 3){
                $commission = 10000 * $investment_money_amount * $commission_per/100;
                $deposit = $commission*$web_config['task_deposit_percent']/100;
                $sponsorship_money = $commission*$web_config['task_sponsorship_money_percent']/100;
            }else{
                $commission = 10000 * $commission;
                $deposit = 1.0*$commission*$sub_num*$web_config['task_deposit_percent']/100;
                $sponsorship_money = 1.0*$commission*$sub_num*$web_config['task_sponsorship_money_percent']/100;
            }

            $insert_arr = array(
                'logo'=>$logo,
                'uid'=>$user_info['user_id'],
                'plat_name'=>$plat_name,
                'cate_id'=>$cate_id,
                'content'=>$content,
                'sub_num'=>$sub_num,
                'commission'=>$commission,
                'ups_commission'=>$ups_commission,
                'hiups_commission'=>$hiups_commission,
                'add_time'=>time(),
                'deposit'=>$deposit,
                'sponsorship_money'=>$sponsorship_money,
                'validate'=>$validate,
                'redirect_url'=>$redirect_url,
                'count_url'=>$count_url,
                'investment_money'=>$investment_money,
                'investment_day'=>$investment_day,
                'expected_money'=>$expected_money,
                'task_tag'=>$task_tag,
                'img_list'=>$img_list,
                'description'=>$description,
                'invite_code'=>$invite_code,
                'bonus'=>$bonus,
                'investment_money_amount'=>$investment_money_amount,
                'min_investment_money'=>$min_investment_money,
                'max_investment_money'=>$max_investment_money,
                'commission_per'=>$commission_per,
                'interest_rate'=>$interest_rate,
            );

            $this->task_model->add_task($insert_arr);
            $tid = $this->db->insert_id();
            //任务标题自动生成（AB理财 投资金额2w 期限30天 佣金Xxx员 理财任务）

            $new_tid = encrypt_wenda_id($tid);
            $task = $this->task_model->task_detail($tid);
            $where = array('tid'=>$tid);
            if($task['cate_id'] == 1){
                $new_title = $task['plat_name'].'投资金额'.$task['investment_money'].'元'.'期限'.$investment_day.'天'."佣金".($commission/10000).'元';
            }elseif($task['cate_id'] == 3){
                $new_title = $task['plat_name'].$task['cate_name']."佣金比例".$task['commission_per'].'%';
            }
            else{
                $new_title = $task['plat_name'].$task['cate_name']."佣金".($commission/10000).'元';
            }
            $update_arr = array(
                'title'=>$new_title
            );
            $this->task_model->update_task($update_arr,$where);
            //echo $this->db->last_query();exit();
            $mess['reqStatus'] = true;
            //$mess['url'] = web_url("/task/index");;
            //添加Log
            $log_content =  $this->task_model->log_content();
            $log_arr = array(
                'type_id'=>$tid,
                'uid'=>$user_info['user_id'],
                'type' => 1,
                'content'=>$log_content['add_task'],
                'add_time'=>time(),
            );
            $this->task_model->add_subtasks_log($log_arr);
            $new_tid = encrypt_wenda_id($tid);
            $mess['url'] = "/task/pay.html?tid={$new_tid}";
            $mess['errorMsg'] = "提交成功";
            $mess['word'] = '前往支付';
            echo JSON($mess);exit;
        }

        $tag = $this->db->select("id,name")->from("dictionary")->where(array("type"=>3))->order_by("id desc")->get()->result_array();
        $this->assign("tags", $tag);

        //给任务分类列表
        $cate_list = $this->task_model->cate_list();
        $this->assign('act','add');
        $this->assign('cate_list',$cate_list);
        $this->display('task/add.html');
    }

    //任务编辑列表
    function edit(){
        $user_info = $this->bbs_userinfo;
        if(!$user_info){//访问超时，请重新登录
            web_redirect("account/login.html".$this->get_next_request_url());
        }
        $tid = decrypt_wenda_id($_GET['tid']);
        $old_tid = $_GET['tid'];
        $task = $this->task_model->task_detail($tid);
        if ($task['uid'] != $user_info['user_id']){
            $this->assign("error", "该任务不属于您发布");
            $this->display('deleted/index.html'.$this->get_next_request_url());
        }

        $task['validate'] = explode(',',$task['validate']);
        $task['img_list'] = explode(',',$task['img_list']);
        $task['task_tag'] = explode(',',$task['task_tag']);
        if(!$task){
            $this->assign("error", "您查找的任务不存在");
            $this->display('deleted/index.html'.$this->get_next_request_url());
        }
        $level = 0;//等级越高越不能改
        if($task['status'] == 3){
            //数量 佣金不能改
            $level = 1;
        }elseif($task['status'] == 2 || $task['status'] == 1){
            //全部不能修改
            web_redirect("task/{$old_tid}.html");exit();
        }
        $task['commission'] = 1.0*$task['commission']/10000;//重新换算成人民币

        $tag = $this->db->select("id,name")->from("dictionary")->where(array("type"=>3))->order_by("id desc")->get()->result_array();
        $this->assign("tags", $tag);

        $cate_list = $this->task_model->cate_list();
        $this->assign('cate_list',$cate_list);
        $this->assign('level',$level);
        $this->assign('task',$task);
        $this->assign('act','edit');
        $this->display('task/add.html');
    }
    //
    function update(){
        $user_info = $this->bbs_userinfo;
        if(!$user_info){//访问超时，请重新登录
            web_redirect("account/login.html".$this->get_next_request_url());
        }
        $web_config = $this->task_model->website_config();
        $title = $_POST['title'];
        $content = $_POST['content'];
        $description = $_POST['description'];
        $sub_num = $_POST['subnum'];
        $commission = $_POST['commission'];
        $ups_commission = $_POST['ups_commission'];
        $hiups_commission = $_POST['hiups_commission'];
        $validate = $_POST['validate'];
        $cate_id = $_POST['cate_id'];
        $logo = $_POST['logo'];
        $invite_code = empty($_POST['invite_code'])?"":trim($_POST['invite_code']);
        $redirect_url = isset($_POST['redirect_url'])?$_POST['redirect_url']:"";
        $investment_money = isset($_POST['investment_money']) ? $_POST['investment_money'] : 0;
        $investment_day = isset($_POST['investment_day']) ? $_POST['investment_day'] : 0;
        $expected_money = isset($_POST['expected_money']) ? $_POST['expected_money'] : 0;
        $task_tag = isset($_POST['tags']) ? $_POST['tags'] : "";
        $img_list = isset($_POST['imglist'])?$_POST['imglist']:array();
        $bonus = empty($_POST['bonus'])?"":trim($_POST['bonus']);
        $img_list_str = "";
        foreach ($img_list as $val){
            if(!empty($val)){
                $img_list_str .= $val.',';
            }
        }
        $img_list = trim($img_list_str,',');
        //$cate_id = 1;//暂时定一个
        $commission = 10000 * $commission;
        $deposit = 1.0*$commission*$sub_num*$web_config['task_deposit_percent']/100;
        $sponsorship_money = 1.0*$commission*$sub_num*$web_config['task_sponsorship_money_percent']/100;
        $tid = $_POST['tid'];
        //判断level,有些值不允许修改，
        if($_POST){
            $update_arr = array(
                'logo'=>$logo,
                'uid'=>$user_info['user_id'],
                'title'=>$title,
                'cate_id'=>$cate_id,
                'content'=>$content,
                'sub_num'=>$sub_num,
                'commission'=>$commission,
                'ups_commission'=>$ups_commission,
                'hiups_commission'=>$hiups_commission,
                'add_time'=>time(),
                'deposit'=>$deposit,
                'sponsorship_money'=>$sponsorship_money,
                'validate'=>$validate,
                'redirect_url'=>$redirect_url,
                'investment_money'=>$investment_money,
                'investment_day'=>$investment_day,
                'expected_money'=>$expected_money,
                'task_tag'=>$task_tag,
                'img_list'=>$img_list,
                'description'=>$description,
                'bonus'=>$bonus,
                'invite_code'=>$invite_code,
            );
            $where = array('tid'=>$tid);
            $this->task_model->update_task($update_arr,$where);
            //
            $log_content =  $this->task_model->log_content();
            $log_arr = array(
                'type_id'=>$tid,
                'uid'=>$user_info['user_id'],
                'type' => 1,
                'content'=>$log_content['update_task'],
                'add_time'=>time(),
            );
            $this->task_model->add_subtasks_log($log_arr);
        }
        $new_tid = encrypt_wenda_id($tid);
        $task = $this->task_model->task_detail($tid);

        if($task['status']>0){
            //跳到详情
            $link = "/task/$new_tid.html";
            $word = '前往详情';
        }else{
            //跳到支付
            $link = "/task/pay.html?tid={$new_tid}";
            $word = '前往支付';
        }
        $result = array(
            "reqStatus" => true,
            "url"=>$link,
            "word"=>$word,
        );
        echo json_encode($result,JSON_HEX_TAG);die;
    }
    //任务列表


    function detail($task_id){
        $tid = $task_id ? decrypt_wenda_id($task_id) : 0;
        $task = $this->task_model->task_detail($tid);
        $web_config = $this->task_model->website_config();
        if(!$task){
            $this->assign("error", "您查找的任务不存在");
            $this->display('deleted/index.html');exit;
        }
        //判断是否是发布方自己的任务，
        $user_info = $this->bbs_userinfo;

        $is_login = empty($user_info)?0:1;
        $task['surplus'] =  $task['sub_num']-$task['snum'];
        if($task['cate_id'] == 4){
            $sql = "select * from tan_subtasks where tid=$tid and is_end!=1";
            $subtask_list = $this->db->query($sql)->row_array();
            $is_zero = empty($subtask_list)?0:1;
        }elseif($task['cate_id'] == 3){
            $investment_money = $this->task_model->subtask_invest_money_count($task['tid']);
            $is_zero = $task['investment_money_amount'] <= $investment_money?1:0;//1表示已经领取完
        }else{
            $is_zero = $task['sub_num'] <= $task['snum']?1:0;//1表示已经领取完(不能在领取)
        }

        $is_end = $task['is_end'];
        $left_time = -1;
        $dead_time = (int)$web_config['task_fail_period'];
        if($is_login){
            $is_my_task = $this->task_model->task_is_my($tid,$user_info['user_id']);
            $my_subtask = $this->subtasks_model->my_subtask($tid,$user_info['user_id']);
            if($is_my_task){
                $status = 1;//发布方的任务，显示编辑
            }elseif($is_end){
                $status = 2;
            }elseif(!$my_subtask && $is_zero){
                //没有申请过任务并且任务已经领完，显示已领完
                $status = 3;
            }elseif(!$my_subtask && !$is_zero){
                //没有申请过任务并且任务数还够，显示立即申请
                $status = 4;
            }elseif($my_subtask && $my_subtask['is_post']==0){
                //未提交认证显示提交认证,需要提供一个left_time,
                $time_dif = time() - $my_subtask['add_time'];
                $left_time = ($dead_time * 3600 - $time_dif)<0 ? 0 :$dead_time * 3600 - $time_dif;
                $status = 5;
            }elseif($my_subtask && $my_subtask['is_post']==1 && $my_subtask['status']==0){
                //已提交认证 子任务没有被审核，显示修改认证和查看
                $status = 6;
            }elseif($my_subtask && $my_subtask['is_post']==1 && $my_subtask['status']==1){
                //已提交认证 子任务没有被审核，只显示查看
                $status = 7;
            }elseif($my_subtask['status']==2){
                //申诉中显示查看
                $status = 8;
            }else{
                $status = -1;
            }
        }
        else{
            if($is_end){
                $status = 2;
            }elseif($is_zero){
                //没有申请过任务并且任务已经领完，显示已领完
                $status = 3;
            }else{
                $status = 4;
            }
        }
//        $is_update = 0;
//        if($task['is_post']==1 && $task['status']!=1 && $task['is_end']==0){
//            $is_update = 1;
//        }
        if ($task['task_tag']){
            $task['task_tags'] = explode(',',$task['task_tag']);
        }
        $task['commission'] = 1.0*$task['commission']/10000;//重新换算成人民币
        /* lht 2018/5/18 14:53 佣金区间 */
        $task['min_commission'] = round(1.0 * $task['commission_per'] * $task['min_investment_money']/100) ;
        $task['max_commission'] = round(1.0 * $task['commission_per'] * $task['max_investment_money']/100) ;

        $task['profit_amount'] = $task['commission']+$task['expected_money']+$task['bonus'];//预期总收益
        $task['img_list'] = $task['img_list']?explode(',',$task['img_list']):array();
        $task['validate'] = $task['validate']?explode(',',$task['validate']):array();
        $recommend_where = "t.is_delete=0 and t.status=1 and t.cate_id=".$task['cate_id']." and t.tid<>".$task['tid'];
        $recommend_list = $this->task_model->task_list($recommend_where,1,4);
        foreach ($recommend_list as $reitem=>$reval){
            $recommend_list[$reitem]['link'] = "/task/".encrypt_wenda_id($reval['tid']).".html";
            $recommend_list[$reitem]['surplus'] = $reval['sub_num']-$reval['snum'];
            $recommend_list[$reitem]['logo'] = $reval['logo']? $reval['logo']:"/static/default/img/nopic.png";
            $recommend_list[$reitem]['commission'] = 1.0*$reval['commission']/10000;
            $recommend_list[$reitem]['surplus'] = $reval['sub_num']-$reval['snum'];
            $recommend_list[$reitem]['overplus'] = ($recommend_list[$reitem]['surplus']/$reval['sub_num'])*100;
            $recommend_list[$reitem]['profit_amount'] = $recommend_list[$reitem]['commission']+$reval['expected_money']+$reval['bonus'];
            $recommend_list[$reitem]['investment_money_amount'] =  $reval['investment_money_amount'];
            $recommend_list[$reitem]['max_investment_money'] =  $reval['max_investment_money'];
            $recommend_list[$reitem]['max_profit_amount'] = round($reval['commission_per']*$reval['max_investment_money']);
            $investment_money = $this->task_model->subtask_invest_money_count($reval['tid']);
            $surplus_money = $reval['investment_money_amount']-$investment_money;

            $overplus_money = ($surplus_money/$reval['investment_money_amount'])*100;
            $recommend_list[$reitem]['surplus_money'] = $surplus_money;
            $recommend_list[$reitem]['overplus_money'] = $overplus_money;
            if ($reval['task_tag']){
                $task_tag = explode(',',$reval['task_tag']);
                foreach ($task_tag as $tag_key=>$tag_val){
                    $recommend_list[$reitem]['tag_span'] .= '<span class="label">'.$tag_val.'</span>';
                }
            }

        }

        $task['_invite'] = empty($task['invite_code'])?0:1;
        $task['tid'] = $task_id;//用处理过得tid
        //$this->assign('is_update',$is_update);

        //剩余可领取的额度
        $task['min_over'] = $task['min_investment_money'];
        $task_max_investment_money = $task['max_investment_money'];
        //剩余金额
        $investment_money = $this->task_model->subtask_invest_money_count($tid);
        $task['max_over'] = $task['investment_money_amount']-$investment_money;
        $task['can_recive_money'] = $task['max_over'] > $task['max_investment_money']? $task['max_investment_money']:$task['max_over'] ;
        $this->assign('dead_time',$dead_time);
        $this->assign('left_time',$left_time);
        $this->assign('status',$status);
        $this->assign('task',$task);
        $this->assign('recommend_list',$recommend_list);
        $this->display('task/detail.html');
    }

    /**
     * 主任务列表
     */
    function mlist(){
        if($_POST){
            $pageIndex = isset($_REQUEST['pageIndex']) ? trim($_REQUEST['pageIndex']) : 0;
            $where = "t.is_delete=0 and t.status=1";
            $count_where = "is_delete=0 and status=1";
            $records_per_page = 10;
            $totalCount = $this->task_model->task_count($count_where);
            $list= $this->task_model->task_list($where,$pageIndex+1,$records_per_page);


            foreach ($list as $key=>$val){
                $tid = $val['tid'] ? encrypt_wenda_id($val['tid']) : 0;
                $link = "/task/{$tid}.html";
                $str = '<div class="location">
					<div class="card-list">
						<div class="con fr" style="width:100%">
							<div class="title">
								<a href="'.$link.'" class="name fl">'.$val['title'].'</a>
								<a href="'.$link.'" target="_blank" class="card-choice fr" >查看详情<b class="icon icon-read-more"></b></a>
								<div class="clear"></div>
								<span>发布人：'.$val['username'].'</span>
							</div>
							<div class="card-txt mt10">
								<ul>
									<li><span>任务期限：</span>'.$val['limit_hour'].'小时</li>
									<li><span>任务数量：</span>'.$val['sub_num'].'</li>
								
								</ul>
								<ul>
									<li><span>已领取数量：</span>'.$val['snum'].'</li>
									<li><span>佣金：</span>'.$val['commission'].'元</li>
                                    
								</ul>';

				            if($val['is_end']==1){
                                $str.='<a href="javascript:void(0);" onclick="" target="_blank" class="apply-button-end fr">已结束</a>';
                            }elseif($val['sub_num']<=$val['snum']){
                                $str.='<a href="javascript:void(0);" onclick="" target="_blank" class="apply-button-end fr">已领完</a>';
                            }else{
                                $str.='<a href="javascript:void(0);" onclick="ajaxApply('.$tid.')" class="apply-button fr">立即领取 </a>';
                            }


								$str.='<div class="clear"></div>
							</div>
						</div>
						<div class="clear"></div>
					</div>
							
				</div>';
                $list[$key]['str'] = str_replace('"', "'", $str);
            }

            $result = array(
                "reqStatus" => true,
                "data" => array(
                    "totalCount" => $totalCount ? $totalCount : 0,
                    "pageIndex" => $pageIndex,
                    "list" => $list
                )
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }



    //提交申请（本质就是添加子任务）
    function ajax_apply(){
        $user_info = $this->bbs_userinfo;
        $apply_investment_money = $_REQUEST['investment_money'];
        //没登录返回没有登录的信息
        if(!$user_info){
            $result = array(
                "reqStatus" => true,
                'msg'=>'请登录再提交申请',
                'code'=>0,
                'link'=>'/account/login.html',
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
        //1.自己的任务不能领取
        $tid = decrypt_wenda_id($_POST['tid']);//真实id
        $invite_code = empty($_POST['invite_code'])?"":$_POST['invite_code'];
        $uid = $user_info['user_id'];
        $new_tid = encrypt_wenda_id($tid);
        $link = "/task/{$new_tid}.html";
        $task = $this->task_model->task_detail($tid);

        if($task['is_pause']==1){
            $result = array(
                "reqStatus" => true,
                'msg'=>'此任务已暂停领取',
                'link'=>$link,
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
        if($this->task_model->task_is_my($tid,$uid)){
            $result = array(
                "reqStatus" => true,
                'msg'=>'此任务为您发布的任务',
                'link'=>$link,
            );
        }else {
            if (!$this->subtasks_model->my_subtask($tid, $uid)) {
                //判断任务是否需要邀请码
                if (!empty($task['invite_code']) && empty($invite_code)) {
                    $result = array(
                        "reqStatus" => true,
                        'msg' => '此任务领取需要邀请码',
                        'link' => $link,
                    );
                    echo json_encode($result, JSON_HEX_TAG);
                    die;
                }
                if (!empty($task['invite_code']) && $task['invite_code'] != $invite_code) {
                    $result = array(
                        "reqStatus" => true,
                        'msg' => '邀请码错误',
                        'link' => $link,
                    );
                    echo json_encode($result, JSON_HEX_TAG);
                    die;
                }
                //已完成任务数量 + 正在进行中的数量 >= 任务总数

                if ($task['cate_id'] == 3) {
                    $investment_money = $this->task_model->subtask_invest_money_count($tid);
                    $surplus_money = $task['investment_money_amount'] - $investment_money;
                    $insert_arr = array(
                        'uid' => $uid,
                        'tid' => $tid,
                        'task_sn' => 'S' . date('YmdHis') . rand(1000, 9999),
                        'add_time' => time(),
                        'investment_money'=>$apply_investment_money
                    );
                    $task = $this->task_model->task_detail($tid);
                    $msg = "领取成功";
                    if ($surplus_money<=0) {
                        $result = array(
                            "reqStatus" => true,
                            'msg' => "任务已领完",
                            'link' => $link,
                        );
                        echo json_encode($result,JSON_HEX_TAG);die;
                    }elseif($apply_investment_money>$surplus_money){
                        $result = array(
                            "reqStatus" => true,
                            'msg' => "超过可领取限制",
                            'link' => $link,
                        );
                        echo json_encode($result,JSON_HEX_TAG);die;
                    }

                    if($apply_investment_money<$task['min_investment_money'] || $apply_investment_money>$task['max_investment_money']){
                        $result = array(
                            "reqStatus" => true,
                            'msg' => "领取金额错误",
                            'link' => $link,
                        );
                        echo json_encode($result,JSON_HEX_TAG);die;
                    }
                    $this->subtasks_model->add_task($insert_arr);
                    $sid = $this->db->insert_id();
                    $result = array(
                        "reqStatus" => true,
                        'msg' => $msg,
                        'link' => $link,
                    );
                    //添加Log
                    $log_content = $this->task_model->log_content();
                    $log_arr = array(
                        'type_id' => $sid,
                        'uid' => $user_info['user_id'],
                        'type' => 2,
                        'content' => $log_content['add_subtasks'],
                        'add_time' => time(),
                    );
                    $this->task_model->add_subtasks_log($log_arr);
                } else {
                    $num = $this->subtasks_model->count_subtask($tid);

                    if ($num < $task['sub_num']) {
                        $insert_arr = array(
                            'uid' => $uid,
                            'tid' => $tid,
                            'task_sn' => 'S' . date('YmdHis') . rand(1000, 9999),
                            'add_time' => time(),
                        );
                        $task = $this->task_model->task_detail($tid);
                        $msg = "领取成功";
                        if ($task['snum'] >= $task['sub_num']) {
                            $msg = '任务已领完';
                        }
                        if($task['cate_id'] == 4){
                            $insert_arr['qualification'] = 0;
                        }
                        $this->subtasks_model->add_task($insert_arr);
                        $sid = $this->db->insert_id();
                        $result = array(
                            "reqStatus" => true,
                            'msg' => $msg,
                            'link' => $link,
                        );
                        //添加Log
                        $log_content = $this->task_model->log_content();
                        $log_arr = array(
                            'type_id' => $sid,
                            'uid' => $user_info['user_id'],
                            'type' => 2,
                            'content' => $log_content['add_subtasks'],
                            'add_time' => time(),
                        );
                        $this->task_model->add_subtasks_log($log_arr);
                    } else {
                        $result = array(
                            "reqStatus" => true,
                            'msg' => "任务已被领完",
                            'link' => $link
                        );
                    }
                }

            } else{
                $result = array(
                    "reqStatus" => true,
                    'msg'=>'已有申请',
                    'link'=>$link,
                );
            }
        }
        //2.不能重复领取

        //判断这个人这个任务是不是有正在进行中的，有就什么都不干，直接跳到详情页


        echo json_encode($result,JSON_HEX_TAG);die;
    }

    function ajax_cancel_apply(){
        //is_end=2 status=4
        $user_info = $this->bbs_userinfo;
        $tid = decrypt_wenda_id($_POST['tid']);//真实id
        $uid = $user_info['user_id'];
        //没登录返回没有登录的信息
        if(!$user_info){
            $result = array(
                "reqStatus" => true,
                'msg'=>'请登录再提交申请',
                'code'=>0,
                'link'=>'/account/login.html',
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
        //
        $update_data = array(
            'is_end'=>2,
            'status'=>4
        );
        $where = array('tid'=>$tid,'uid'=>$uid);
        if($this->subtasks_model->update_subtask($update_data,$where)) {
            //判断任务是否需要邀请码
            $result = array(
                "reqStatus" => true,
                'msg' => '申请成功',
            );
            echo json_encode($result, JSON_HEX_TAG);
            die;
        }else{
            $result = array(
                "reqStatus" => true,
                'msg' => '申请失败',
            );
            echo json_encode($result, JSON_HEX_TAG);
            die;
        }

    }
    function update_subtask(){
        $tid = decrypt_wenda_id($_POST['tid']);
        $sid = $_REQUEST['sid'];
        $validate = $_REQUEST['validate'];
        $user_info = $this->bbs_userinfo;
        if(!$user_info){//访问超时，请重新登录
            //web_redirect("account/login.html".$this->get_next_request_url());
        }
        $update_arr = array(
            'validate'=>$validate,
            'is_post'=>1,
            'receive_time'=>time(),
        );
        $where = array(
            'uid'=>$user_info['user_id'],
            'tid'=>$tid,
            'is_end'=>0,
        );
        $this->subtasks_model->update_subtask($update_arr,$where);

        $result = array(
            "reqStatus" => true,
            "data" => array(),
            "msg"=>'提交成功'
        );
        //添加Log
        $log_content =  $this->task_model->log_content();
        $log_arr = array(
            'type_id'=>$sid,
            'uid'=>$user_info['user_id'],
            'type' => 2,
            'content'=>$log_content['add_subtasks'],
            'add_time'=>time(),
        );
        $this->task_model->add_subtasks_log($log_arr);
        echo json_encode($result,JSON_HEX_TAG);die;
    }

    //
    function info(){
       // 这个任务 提交的验证条件
        $real_tid = $_GET['tid'] ? decrypt_wenda_id($_GET['tid']) : 0;
        $task = $this->task_model->task_detail($real_tid);
        $uid = $this->userinfo['user_id'];
        //获取subtask的validate，
        $sql = "select * from tan_subtasks where uid={$uid} and tid={$real_tid} and is_end=0";
        $subtask_info = $this->db->query($sql)->row_array();
        $sub_validate = unserialize($subtask_info['validate']);
        $res = array(
            'validate'=>$task['validate']?explode(',',$task['validate']):array(),
            'img_list'=>$task['img_list']?explode(',',$task['img_list']):array(),
            'tid'=>encrypt_wenda_id($task['tid']),
        );
        $this->assign('validate',$sub_validate);
        $this->assign('task',$res);
        $this->display('task/info.html');
    }

    function pay(){
        $tid = empty($_GET['tid'])?0:$_GET['tid'];
        $real_tid = decrypt_wenda_id($tid);
        $task = $this->task_model->task_detail($real_tid);
        //var_dump($this->bbs_userinfo);exit();
        if(!$task){
            $this->assign("error", "您查找的任务不存在");
            $this->display('deleted/index.html');exit;
        }
        //判断是否是发布方自己的任务，
        $user_info = $this->bbs_userinfo;
        if(!$user_info){//访问超时，请重新登录
            web_redirect("account/login.html".$this->get_next_request_url());
        }
        if ($task['uid'] != $user_info['user_id']){
            $this->assign("error", "该任务不属于您发布");
            $this->display('deleted/index.html'.$this->get_next_request_url());
        }
        $uid = $user_info['user_id'];
        $web_config = $this->task_model->website_config();
        $commission = $task['commission'];
        $sub_num = $task['sub_num'];
        $deposit = $task['deposit'];
        $sponsorship_money = $task['sponsorship_money'];

        if($task['cate_id']==3){
            $total = 10000*$task['investment_money_amount'] * $task['commission_per']*1.0/100 + $deposit + $sponsorship_money;
        }else{
            $total = $commission * $sub_num + $deposit + $sponsorship_money;
        }
        $new_task = array(
            'cate_id'=>$task['cate_id'],
            'commission_per'=>$task['commission_per'],
            'investment_money_amount'=>$task['investment_money_amount']*10000,
            'tid'=> $tid,
            'commission'=>$commission,
            'sub_num'=>$sub_num,
            'deposit'=>$deposit,
            'sponsorship_money'=>$sponsorship_money,
            'total'=>$total,
        );
        $this->assign('task',$new_task);
        $this->display("task/pay.html");
    }

    function ajax_pay(){
        $tid = empty($_POST['tid'])?0:$_POST['tid'];
        $cate_id = empty($_POST['cate_id'])?0:$_POST['cate_id'];
        $real_tid = decrypt_wenda_id($tid);
        $task = $this->task_model->task_detail($real_tid);
        //判断是否是发布方自己的任务，
        $user_info = $this->bbs_userinfo;
        if(!$user_info){//访问超时，请重新登录
            $result = array(
                "reqStatus" => true,
                'msg'=>'请登录再提交申请',
                'code'=>0,
                'link'=>'/account/login.html',
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
        $uid = $user_info['user_id'];
        $web_config = $this->task_model->website_config();
        $commission = $task['commission'];
        $sub_num = $task['sub_num'];
        $deposit = $task['deposit'];
        $sponsorship_money = $task['sponsorship_money'];
        $investment_money_amount = $task['investment_money_amount'];
        $commission_per = $task['commission_per'];
        if($cate_id == 3){
            $total = $investment_money_amount * 1.0*$commission_per/100;
        }else{
            $total = $commission * $sub_num + $deposit + $sponsorship_money;
        }

        //echo $uid;exit();
        $account = $this->account_model->get($uid);
        //还要更新task的赞助费和保证金

        if($total > $account['balance']){
            $result = array(
                "reqStatus" => false,
                'errorMsg'=>'账户余额不足',
                "link"=>'',
            );
        }else{
            //1.相关金额修改
            $update_account = array(
                'balance' => $account['balance'] - $total,
                'expend' => $account['expend'] + $total,
            );
            $this->account_model->update($update_account,$uid);
            //2task表相关信息更新
            $update_data = array(
                'deposit'=>$deposit,
                'sponsorship_money'=>$sponsorship_money,
                'status'=>3
            );
            $task_where = array('tid'=>$real_tid);
            $this->task_model->update_task($update_data,$task_where);
            //3.
            $month = date('Ym');
            $day = date('Ymd');
            $finance_data = array();
            $finance_data['user_id'] = $uid;
            $finance_data['content'] = '发布任务支付'.$total.'溜溜币';
            $finance_data['finance'] = $total;
            $finance_data['finance_balance'] = $account['balance'] - $total;
            $finance_data['reward_type'] = 'task_publish';
            $finance_data['type'] = 2;
            $finance_data['create_time'] = time();
            $finance_data['month'] = $month;
            $finance_data['day'] = $day;
            $this->finance_list_model->insert($finance_data);
            //2.log记录
            $log_data = array(
                'user_id'=>$uid,
                'events'=>'pay',
                'content'=>'支付成功',
                'ip'=>$this->input->ip_address(),
            );
            $this->users_log_model->insert($log_data);
            //任务日志记录
            //添加Log
            $log_content =  $this->task_model->log_content();
            $log_arr = array(
                'type_id'=>$real_tid,
                'uid'=>$user_info['user_id'],
                'type' => 2,
                'content'=>$log_content['pay_task'],
                'add_time'=>time(),
            );
            $this->task_model->add_subtasks_log($log_arr);
            $result = array(
                "reqStatus" => true,
                'msg'=>'支付成功',
                'link'=>'/account/taskrel.html'
            );

        }
        echo json_encode($result,JSON_HEX_TAG);die;
    }

    //首页列表页
    function new_mlist(){
        if($_POST){
            $pageIndex = isset($_REQUEST['pageIndex']) ? trim($_REQUEST['pageIndex']) : 0;

            $type = isset($_REQUEST['type']) ? trim($_REQUEST['type']) : 0;
            $term = isset($_REQUEST['term']) ? trim($_REQUEST['term']) : 0;
            $amount = isset($_REQUEST['amount']) ? trim($_REQUEST['amount']) : 0;
            $tags = isset($_REQUEST['tags']) ? trim($_REQUEST['tags']) : '';
            $keyword = isset($_REQUEST['keyword']) ? trim($_REQUEST['keyword']) : '';

            $where = " 1=1";
            if (!empty($keyword)){
                $where .= " and t.title like '%$keyword%' ";
            }

            if ($type > 0){
                $where .= " and t.cate_id=$type ";
            }else{
                $where .= " and t.cate_id<>4 ";
            }

            if (!empty($tags) ){
                $where .= " and t.task_tag like '%$tags%' ";
            }
            if ($term){
                switch ($term){
                    case 1:
                        $where .= " and t.investment_day>0 and t.investment_day<=30 ";
                        break;
                    case 2:
                        $where .= " and t.investment_day>30 and t.investment_day<=90 ";
                        break;
                    case 3:
                        $where .= " and t.investment_day>90 and t.investment_day<=180 ";
                        break;
                    case 4:
                        $where .= " and t.investment_day>180 and t.investment_day<=365 ";
                        break;
                    case 5:
                        $where .= " and t.investment_day>365 ";
                        break;
                    default:
                        $where .= "";
                        break;
                }
            }
            if ($amount){
                switch ($amount){
                    case 1:
                        $where .= " and t.investment_money>0 and t.investment_money<=1000 ";
                        break;
                    case 2:
                        $where .= " and t.investment_money>1000 and t.investment_money<=10000 ";
                        break;
                    case 3:
                        $where .= " and t.investment_money>10000 and t.investment_money<=50000 ";
                        break;
                    case 4:
                        $where .= " and t.investment_money>50000 ";
                        break;
                    default:
                        $where .= "";
                        break;
                }
            }


            $where .= " and t.is_delete=0 and t.status=1";

            $records_per_page = 12;
            $totalCount = $this->task_model->task_count($where);

            $list= $this->task_model->task_list($where,$pageIndex+1,$records_per_page);

            foreach ($list as $key=>$val){
                $tid = $val['tid'] ? encrypt_wenda_id($val['tid']) : 0;
                $tag_span = '';
                if ($val['task_tag']){
                    $task_tag = explode(',',$val['task_tag']);
                    foreach ($task_tag as $tag_key=>$tag_val){
                        $tag_span .= '<span class="label">'.$tag_val.'</span>';
                    }
                }
                $can_revieve = 1;//默认可以领取
                $surplus = $val['sub_num']-$val['snum'];
                $overplus = ($surplus/$val['sub_num'])*100;
                $val['logo'] = $val['logo']? $val['logo']:"/static/default/img/nopic.png";
                $link = "/task/{$tid}.html";
                $val['commission'] = 1.0*$val['commission']/10000;

                $over_html = '<!--剩余数量-->
                                <div class="last-amount f-cb">
                                    <span class="txt">剩余数量</span>
                                    <div class="loadbox">
                                        <dl class="big-barbox">
                                            <dd class="barline">
                                                <div style="width: '.$overplus.'%;" class="charts"></div>
                                            </dd>
                                        </dl>
                                    </div>
                                    <span style="margin-top: 1px;" class="txt"><font>'.$surplus.'</font>/'.$val['sub_num'].'</span>
                                </div>';

                $str = '<li>
                            <div class="list-head f-cb">
                                <img src="'.$val['logo'].'" alt="'.$val['title'].'" class="fl logo">
                                <div class="label-box fr">
                                    '.$tag_span.'
                                </div>
                            </div>
                            <div class="list-content">';
                if($val['cate_id']==1){
                    if($surplus <=0){
                        $can_revieve = 0;
                    }
                    $profit_amount = $val['commission']+$val['expected_money']+$val['bonus'];
                    $str.='<!--预期总收益-->
                                <div class="sort-money f-cb">
                                    <div class="title-label fl">理财任务</div>
                                    <div class="expect-return fl">
                                        <h5><b>'.$profit_amount.'</b>元</h5>
                                        <p>预期总收益</p>
                                    </div>
                                </div>
                                <!--投资金额、周期-->
                                <div class="amount-cycle f-cb">
                                    <div class="fl amount">
                                        <p>'.$val['investment_money'].'元</p><span>投资金额</span>
                                    </div>
                                    <div class="fr cycle">
                                        <p>'.$val['investment_day'].'天</p><span>投资周期</span>
                                    </div>
                                </div>';
                }
                if($val['cate_id']==3){
                    $profit_amount = $val['commission']+$val['expected_money']+$val['bonus'];

                    $max_profit_amount = round($val['commission_per']*$val['max_investment_money'])/100;
                    $str.='<!--预期总收益-->
                                <div class="sort-money f-cb">
                                    <div class="title-label fl">区间理财</div>
                                    <div class="expect-return fl">
                                        <h5><b>'.$val['commission_per'].'</b>%</h5>
                                        <p>佣金比例</p>
                                    </div>
                                </div>
                                <!--投资金额、周期-->
                                <div class="amount-cycle f-cb">
                                    <div class="fl amount">
                                        <p>'.$val['max_investment_money'].'元</p><span>投资金额</span>
                                    </div>
                                    <div class="fr cycle">
                                        <p>'.$val['investment_day'].'天</p><span>投资周期</span>
                                    </div>
                                </div>';
                    /* lht 2018/5/18 16:00 剩余额度 */
                    //统计这个任务已经领取的额度总和
                    $investment_money = $this->task_model->subtask_invest_money_count($val['tid']);
                    $surplus_money = $val['investment_money_amount']-$investment_money;
                    $overplus_money = ($surplus_money/$val['investment_money_amount'])*100;
                    if($surplus_money <= 0){
                        $can_revieve = 0;
                     }
                    $over_html = '<!--剩余数量-->
                                <div class="last-amount f-cb">
                                    <span class="txt">剩余额度</span>
                                    <div class="loadbox">
                                        <dl class="big-barbox">
                                            <dd class="barline">
                                                <div style="width: '.$overplus_money.'%;" class="charts"></div>
                                            </dd>
                                        </dl>
                                    </div>
                                    <span style="margin-top: 1px;" class="txt"><font>'.$surplus_money.'</font>/'.$val['investment_money_amount'].'</span>
                                </div>';
                }
                if ($val['cate_id']==2){
                    if($surplus <=0){
                        $can_revieve = 0;
                    }
                    $str .= '<div class="sort-money f-cb">
                                <div class="title-label fl">注册任务</div>
                                <div class="expect-return fl">
                                    <h5><b>'.$val['commission'].'</b>元</h5>
                                    <p>佣金</p>
                                </div>
                            </div>
                            <div class="amount-cycle f-cb">
                                <p class="item-title textnum35">'.$val['title'].'</p>
                            </div>';
                }
                if ($val['cate_id']==4){
                    $sql = "select * from tan_subtasks where tid={$val['tid']} and is_end!=1";
                    $subtask_list = $this->db->query($sql)->row_array();
                    $can_revieve = empty($subtask_list)?1:0;
                    $str .= '<div class="sort-money f-cb">
                                <div class="title-label fl">B 2 B任务</div>
                                <div class="expect-return fl">
                                    <h5><b>'.$val['commission'].'</b>元</h5>
                                    <p>佣金</p>
                                </div>
                            </div>
                            <div class="amount-cycle f-cb">
                                <p class="item-title textnum35">'.$val['title'].'</p>
                            </div>';
                    $over_html = '';
                }
                //<!--查看-->
                if($val['is_end']==1){
                    $str.='<div class="look-box"><a href="'.$link.'" class="look-btn" style="background: #d4d4d4">已结束</a></div>';
                    $str.='</div>
                        </li>';
                }elseif($can_revieve==0){
                    $str.='<div class="look-box"><a href="'.$link.'" class="look-btn" style="background: #d4d4d4">已领完</a></div>';

                    $str.= $over_html . '
                            </div>
                        </li>';
                }else{

                    $str.='<div class="look-box"><a href="'.$link.'" class="look-btn">查看</a></div>';
                    $str.= $over_html . '
                            </div>
                        </li>';
                }
                $list[$key]['can_revieve'] = $can_revieve;
                $list[$key]['str'] = str_replace('"', "'", $str);
            }

            $result = array(
                "reqStatus" => true,
                "data" => array(
                    "totalCount" => $totalCount ? $totalCount : 0,
                    "pageIndex" => $pageIndex,
                    "list" => $list
                )
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    function ajax_get_task_cate(){
        $cate_list = $this->task_model->cate_list();
        foreach ($cate_list as $item=>$value){
            $cate_list[$item]['cate_field'] = explode(',',$value['cate_field']);
        }
        echo json_encode($cate_list,JSON_HEX_TAG);die;
    }


    function submit_validate(){
        $validate = array();
        if(isset($_POST['name'])){
            $validate['name'] = $_POST['name'];
        }

        if(isset($_POST['phone'])){
            $validate['phone'] = $_POST['phone'];
        }

        if(isset($_POST['identity'])){
            $validate['identity'] = $_POST['identity'];
        }

        if(isset($_POST['img_list'])){
            $validate['img_list'] = $_POST['img_list'];
        }
        $tid = decrypt_wenda_id($_POST['tid']);
        $user_info = $this->bbs_userinfo;
        $uid = $user_info['user_id'];
        if(!$user_info){//访问超时，请重新登录
            $result = array(
                "reqStatus" => true,
                'msg'=>'请登录再提交验证信息',
                'code'=>0,
                'link'=>'/account/login.html',
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }


        //找子任务信息
        $sql = "select * from tan_subtasks where uid={$uid} and tid={$tid} and is_end=0";
        $subtask_info = $this->db->query($sql)->row_array();
        if(empty($subtask_info)){
            echo json_encode(array(),JSON_HEX_TAG);die;
        }
        $sid = $subtask_info['sid'];
        $where = array('sid'=>$sid);
        $update_arr = array(
            'validate'=>serialize($validate),
            'is_post'=>1,
            'receive_time'=>time(),
        );
        $this->subtasks_model->update_subtask($update_arr,$where);
        $result = array(
            "reqStatus" => true,
            "data" => array(),
            "msg"=>'提交成功',
            "link"=>'/task/'.$_POST['tid'].'.html',
        );

        //添加Log
        $log_content =  $this->task_model->log_content();
        $log_arr = array(
            'type_id'=>$sid,
            'uid'=>$user_info['user_id'],
            'type' => 2,
            'content'=>$log_content['validate'],
            'add_time'=>time(),
        );
        $this->task_model->add_subtasks_log($log_arr);
        echo json_encode($result,JSON_HEX_TAG);die;

    }

    //任务跳转到外部链接
    function task_redirect(){
        $tid = $_GET['tid'];
        $real_tid = decrypt_wenda_id($tid);
        $task = $this->task_model->task_detail($real_tid);
        $tid =1;
        $data['type'] = 2;
        $data['type_val'] = $tid;//任务id
        $data['jump_url'] = $task['redirect_url'];
        $data['request_ip'] = $this->input->ip_address();
        $data['request_from'] = $_SERVER['HTTP_REFERER'];
        $data['request_time'] = time();
        $this->task_model->add_reload_log($data);
        redirect($task['redirect_url']);
    }

    public function task_excel(){
        $tid = decrypt_wenda_id($_GET['tid']);
        //获取主任务的信息
        $task = $this->task_model->task_detail($tid);
        //检查tid是不是自己的
        $ListRowData = $this->task_model->task_reveive_record($tid);
        $this->load->library('Export');
        $HeadData = array('记录编号','标题','用户名','领取人','姓名','手机号','身份证','提交时间','领取时间','审核状态');
        $filename =$task['title'].'--'.date('Y-m-d');
        echo $this->export->users($HeadData,$ListRowData,$filename);exit;
    }
    //b TO b 任务列表
    public function task_bb_list(){
        $is_end =  isset($_REQUEST['is_end']) ? trim($_REQUEST['is_end']) : 0;
        $pageIndex = isset($_REQUEST['pageIndex']) ? trim($_REQUEST['pageIndex']) : 0;
        $where = " t.cate_id=4 ";
        if($is_end > 0){
            $where .= " t.is_end={$is_end} ";
        }
        $records_per_page = 12;
        $totalCount = $this->task_model->task_count($where);
        $list= $this->task_model->task_list($where,$pageIndex+1,$records_per_page);
        $result = array(
            "reqStatus" => true,
            "data" => array(
                "totalCount" => $totalCount ? $totalCount : 0,
                "pageIndex" => $pageIndex,
                "list" => $list
            )
        );
        echo json_encode($result,JSON_HEX_TAG);die;
    }

    //申请结束子任务
    public function end_subtask(){
        //tid uid sid 去检查
        $tid = decrypt_wenda_id($_REQUEST['tid']);
        $sid = decrypt_wenda_id($_REQUEST['sid']);
        $user_info = $this->bbs_userinfo;
        $uid = $user_info['user_id'];
        //检查是否是uid发布的任务还是自己的任务
        $sql = "select s.uid suid,t.uid tuid from tan_subtasks s left join tan_task t on s.tid = t.tid where s.sid={$sid}";
        $subtask_info = $this->db->query($sql)->row_array();
        if($subtask_info['suid'] == $uid || $subtask_info['tuid'] == $uid){
            $update_sql = "update tan_subtasks set apply_end=1 where sid={$sid}";
            $this->db->query($update_sql);
            $result = array(
                "reqStatus" => true,
                'msg'=>'更新成功',
                'code'=>0,
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }else{
            $result = array(
                "reqStatus" => true,
                'msg'=>'非发布方或者领取方操作',
                'code'=>0,
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
    }
    //l领取方提前结束任务

    //增加金额
    public function add_amount(){
        $user_info = $this->bbs_userinfo;
        if(!$user_info){//访问超时，请重新登录
            $result = array(
                "reqStatus" => false,
                'msg'=>'请登录再提交验证信息',
                'code'=>1,
                'link'=>'/account/login.html',
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
        $uid = $user_info['user_id'];
        $amount = $_REQUEST['amount'];
        //检查这个人的溜溜币是否够
        $account = $this->account_model->get($uid);
        //还要更新task的赞助费和保证金

        if($amount*10000 > $account['balance']){
            $result = array(
                "reqStatus" => false,
                'msg'=>'金额不足',
                'code'=>0
            );
            echo json_encode($result,JSON_HEX_TAG);die;
        }
        $tid = decrypt_wenda_id($_REQUEST['tid']);
        $task = $this->task_model->task_detail($tid);
        $commission = $task['commission'];
        $web_config = $this->task_model->website_config();
        $task_deposit_percent = $web_config['task_deposit_percent'];//押金百分比
        $task_sponsorship_money_percent = $web_config['task_sponsorship_money_percent'];//赞助商百分比
        //流量数
        $percent = 1 + $task_deposit_percent/100 + $task_sponsorship_money_percent/100;
        $num = (int)(10000 * $amount/$percent/$commission);
        $pay_amount = $num * $commission * $percent;
        $update_account = array(
            'balance' => $account['balance'] - $pay_amount,
            'expend' => $account['expend'] + $pay_amount,
        );
        $this->account_model->update($update_account,$uid);
        //2task表相关信息更新
        $sub_num = $task['sub_num'] + $num;
        $update_data = array(
            'sub_num'=>$sub_num,
        );
        $task_where = array('tid'=>$tid);
        $this->task_model->update_task($update_data,$task_where);
        //3.
        $month = date('Ym');
        $day = date('Ymd');
        $finance_data = array();
        $finance_data['user_id'] = $uid;
        $finance_data['content'] = '增值任务金额支付'.$pay_amount.'溜溜币';
        $finance_data['finance'] = $pay_amount;
        $finance_data['finance_balance'] = $account['balance'] - $pay_amount;
        $finance_data['reward_type'] = 'task_publish';
        $finance_data['type'] = 2;
        $finance_data['create_time'] = time();
        $finance_data['month'] = $month;
        $finance_data['day'] = $day;
        $this->finance_list_model->insert($finance_data);
        //2.log记录
        $log_data = array(
            'user_id'=>$uid,
            'events'=>'pay',
            'content'=>'支付成功',
            'ip'=>$this->input->ip_address(),
        );
        $this->users_log_model->insert($log_data);
        //任务日志记录
        //添加Log
        $log_content =  $this->task_model->log_content();
        $log_arr = array(
            'type_id'=>$tid,
            'uid'=>$user_info['user_id'],
            'type' => 2,
            'content'=>$log_content['pay_task'],
            'add_time'=>time(),
        );
        $this->task_model->add_subtasks_log($log_arr);
        $result = array(
            "reqStatus" => true,
            'msg'=>'修改成功',
            'code'=>0,
        );
        echo json_encode($result,JSON_HEX_TAG);die;
    }


}
